package unipi.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import unipi.database.PrivateMessage;
import unipi.helpers.HTMLPages;
import unipi.helpers.LoginCookie;
import unipi.helpers.Table;

public class ViewConversations extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	
	public ViewConversations()
	{
		super();
	}
	
	public void init() throws ServletException
	{
		
	
	}
	
	private String getPage(String uid)
	{
		String content = "<h1>Συζητήσεις</h1>";
		
		List<List<String>> convs = PrivateMessage.getUserRecipients(uid);
		
		if(convs == null)
		{
			content += "Παρουσιάστηκε πρόβλημα κατα την φόρτωση των συζητήσεων σας.";
		}
		else if(convs.size() == 0)
		{
			content += "Δεν υπάρχουν συζητήσεις προς εμφάνιση.";
		}
		else
		{			
			List<String> coltitles = new ArrayList<String>();
			coltitles.add("Όνομα παραλήπτη");
			coltitles.add("Αριθμός μηνυμάτων");
			coltitles.add("Συζήτηση");
			
			Table t = new Table(coltitles);
			
			boolean even = false;
			for(List<String> conv : convs)
			{
				conv.set(0, "<a class=\"genericLink\" href=\"Profile?id=" + conv.get(2) + "\">" + conv.get(0) + "</a>");
				conv.set(2, "<a class=\"genericLink\" href = \"ViewChat?id=" + conv.get(2) + "\">Ανοιγμα συζήτησης</a>");
				t.addRow(conv, even);
				even = !even;
			}
			
			content += t.getHTML();
		}
		
		return HTMLPages.getGeneralPage(content, uid);	
	}
		
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		if(!LoginCookie.authCookie(request))
			response.sendRedirect("Login");
		else
		{
			String uid = LoginCookie.Get(request)[0];
			
			response.setContentType("text/html; charset=UTF-8");	
			PrintWriter out = response.getWriter();
			
			out.println(getPage(uid));
			
			out.close();			
		}
	}
}